package org.dromara.bykt.service.impl;

import cn.hutool.core.util.ObjectUtil;
import org.dromara.bykt.domain.BYKTSysUser;
import org.dromara.bykt.domain.bo.BYKTSysUserBo;
import org.dromara.bykt.domain.bo.BYKTXxmjUserExtBo;
import org.dromara.bykt.domain.vo.BYKTSysUserVo;
import org.dromara.bykt.domain.vo.BYKTXxmjUserExtVo;
import org.dromara.bykt.service.IBYKTXxmjUserExtService;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.DateUtils;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.system.domain.SysUser;
import org.dromara.system.domain.vo.SysUserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.dromara.bykt.mapper.BYKTSysUserMapper;
import org.dromara.bykt.service.IBYKTSysUserService;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 用户信息Service业务层处理
 *
 * @author Hou
 * @date 2025-07-01
 */
@RequiredArgsConstructor
@Service
public class BYKTSysUserServiceImpl implements IBYKTSysUserService {

    private final BYKTSysUserMapper baseMapper;

    @Autowired
    private IBYKTXxmjUserExtService byktxxmjUserExtService;

    /**
     * 查询用户信息
     *
     * @param userId 主键
     * @return 用户信息
     */
    @Override
    public BYKTSysUserVo queryById(Long userId){
        return baseMapper.selectVoById(userId);
    }

    /**
     * 分页查询用户信息列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 用户信息分页列表
     */
    @Override
    public TableDataInfo<BYKTSysUserVo> queryPageList(BYKTSysUserBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<BYKTSysUser> lqw = buildQueryWrapper(bo);
        Page<BYKTSysUserVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的用户信息列表
     *
     * @param bo 查询条件
     * @return 用户信息列表
     */
    @Override
    public List<BYKTSysUserVo> queryList(BYKTSysUserBo bo) {
        LambdaQueryWrapper<BYKTSysUser> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<BYKTSysUser> buildQueryWrapper(BYKTSysUserBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<BYKTSysUser> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(BYKTSysUser::getUserId);
        lqw.eq(bo.getDeptId() != null, BYKTSysUser::getDeptId, bo.getDeptId());
        lqw.like(StringUtils.isNotBlank(bo.getUserName()), BYKTSysUser::getUserName, bo.getUserName());
        lqw.like(StringUtils.isNotBlank(bo.getNickName()), BYKTSysUser::getNickName, bo.getNickName());
        lqw.eq(StringUtils.isNotBlank(bo.getUserType()), BYKTSysUser::getUserType, bo.getUserType());
        lqw.eq(StringUtils.isNotBlank(bo.getEmail()), BYKTSysUser::getEmail, bo.getEmail());
        lqw.eq(StringUtils.isNotBlank(bo.getPhonenumber()), BYKTSysUser::getPhonenumber, bo.getPhonenumber());
        lqw.eq(StringUtils.isNotBlank(bo.getSex()), BYKTSysUser::getSex, bo.getSex());
        lqw.eq(bo.getAvatar() != null, BYKTSysUser::getAvatar, bo.getAvatar());
        lqw.eq(StringUtils.isNotBlank(bo.getPassword()), BYKTSysUser::getPassword, bo.getPassword());
        lqw.eq(StringUtils.isNotBlank(bo.getStatus()), BYKTSysUser::getStatus, bo.getStatus());
        lqw.eq(StringUtils.isNotBlank(bo.getLoginIp()), BYKTSysUser::getLoginIp, bo.getLoginIp());
        lqw.eq(bo.getLoginDate() != null, BYKTSysUser::getLoginDate, bo.getLoginDate());
        if (bo.getBeginCreateTime() != null && bo.getEndCreateTime() != null) {
            lqw.between(BYKTSysUser::getCreateTime, bo.getBeginCreateTime(), bo.getEndCreateTime());
        }
        return lqw;
    }

    /**
     * 新增用户信息
     *
     * @param bo 用户信息
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(BYKTSysUserBo bo) {
        bo.setCreateTime(new Date());
        BYKTSysUser add = MapstructUtils.convert(bo, BYKTSysUser.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setUserId(add.getUserId());
            if (bo.getUserCategory() != null && StringUtils.isNotBlank(bo.getUserCategory())) {
                BYKTXxmjUserExtBo extBo = new BYKTXxmjUserExtBo();
                extBo.setUserId(bo.getUserId());
                extBo.setUserCategory(bo.getUserCategory());
                extBo.setPhoneVerified(bo.getPhoneVerified());
                extBo.setStudyProgress(0L);
                extBo.setRegisterTime(new Date());
                byktxxmjUserExtService.insertByBo(extBo);
            }
        }
        return flag;
    }

    /**
     * 修改用户信息
     *
     * @param bo 用户信息
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(BYKTSysUserBo bo) {
        bo.setUpdateTime(new Date());
        BYKTSysUser update = MapstructUtils.convert(bo, BYKTSysUser.class);
        validEntityBeforeSave(update);
        BYKTXxmjUserExtVo byktXxmjUserExtVo = byktxxmjUserExtService.selectByUserId(bo.getUserId());
        if (byktXxmjUserExtVo != null) {
            if (bo.getUserCategory() != null && StringUtils.isNotBlank(bo.getUserCategory())) {
                BYKTXxmjUserExtBo extBo = new BYKTXxmjUserExtBo();
                extBo.setId(byktXxmjUserExtVo.getId());
                extBo.setUserId(bo.getUserId());
                extBo.setUserCategory(bo.getUserCategory());
                extBo.setPhoneVerified(bo.getPhoneVerified());
                extBo.setStudyProgress(0L);
                extBo.setRegisterTime(new Date());
                byktxxmjUserExtService.updateByBo(extBo);
            }
        } else {
            if (bo.getUserCategory() != null && StringUtils.isNotBlank(bo.getUserCategory())) {
                BYKTXxmjUserExtBo extBo = new BYKTXxmjUserExtBo();
                extBo.setUserId(bo.getUserId());
                extBo.setUserCategory(bo.getUserCategory());
                extBo.setPhoneVerified(bo.getPhoneVerified());
                extBo.setStudyProgress(0L);
                extBo.setRegisterTime(new Date());
                byktxxmjUserExtService.insertByBo(extBo);
            }
        }
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(BYKTSysUser entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除用户信息信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    /**
     * 通过用户名查询用户
     *
     * @param userName 用户名
     * @return 用户对象信息
     */
    @Override
    public BYKTSysUserVo selectUserByUserName(String userName) {
        return baseMapper.selectVoOne(new LambdaQueryWrapper<BYKTSysUser>().eq(BYKTSysUser::getUserName, userName));
    }

    /**
     * 校验用户是否允许操作
     *
     * @param userId 用户ID
     */
    @Override
    public void checkUserAllowed(Long userId) {
        if (ObjectUtil.isNotNull(userId) && LoginHelper.isSuperAdmin(userId)) {
            throw new ServiceException("不允许操作超级管理员用户");
        }
    }

    /**
     * 校验用户是否有数据权限
     *
     * @param userId 用户id
     */
    @Override
    public void checkUserDataScope(Long userId) {
        if (ObjectUtil.isNull(userId)) {
            return;
        }
        if (LoginHelper.isSuperAdmin()) {
            return;
        }
        if (baseMapper.countUserById(userId) == 0) {
            throw new ServiceException("没有权限访问用户数据！");
        }
    }
}
